// JavaScript Document
BingoTouch.init = function () {
    /*清除loginHashMap保存的信息*/
    //BingoTouch.Local.clearHashmap("loginHashMap");
};

BingoTouch.ready = function () {

    var name = BingoTouch.Local.readHashmap("loginHashMap", "username");
    var specSecret = BingoTouch.Local.readHashmap("loginHashMap", "spec_secret");
    var loginId = BingoTouch.Local.readHashmap("loginHashMap", "loginId");

    //自动登录
    var isAutoLogin = BingoTouch.Local.readHashmap("loginHashMap", "isAutoLogin");

    if (isAutoLogin != null && isAutoLogin != "" && isAutoLogin == "true") {
        //应用专用密码登录
        //        var param = { 'userName': name, 'password': specSecret, 'get_spec_secret': false, 'get_service_ticket': false };
        //        BingoTouch.SSO.Login("SPECSECRET", param, function (response) {
        //            /*登录到后台服务*/
        //            AfterSSOLogin();
        //        },
        //        function (code, desc) {
        //            BingoTouch.Common.alert(code, desc);
        //        });
        //        AfterSSOLogin();
        AutoLogin();
    }

    $('#version').html("当前版本：" + BingoTouch.App.getVersionCode());
    if (!isDebug) { //生产环境时检查新版本
        BingoTouch.Common.WebRequest(context_path + 'version.txt', "GET", "", null, false,
        function (str) {
            var v = BingoTouch.Common.string2json(str);
            if (v.ver > BingoTouch.App.getVersionCode()) {
                if (BingoTouch.Common.confirm("最新版本为" + v.ver + "，请点击确定进行应用更新。")) {
                    if (BingoTouch.Device.isAndroid) {
                        BingoTouch.App.download(context_path + 'install/' + v.android, "应用开始下载...", v.android);
                        BingoTouch.Common.alert(v.android + '已经在下载中，下载完成后会提醒您安装。');
                    } else if (BingoTouch.Device.isIOS) {
                        BingoTouch.App.run("itms-services", v.ios);
                    }
                }
            }
        });
    }
};

/*登录事件*/
function Login() {
    if ($("#userName").val() == "" || $("#password").val() == "") {
        BingoTouch.Common.alert("用户信息不能为空！");
        return;
    }
    var name = $("#userName").val();
    var pwd = $("#password").val();

    BingoTouch.WebView.wait(true);

    var getServiceTicket = false;
    var getSpecSecret = false;
    if ($("#cbAuto").attr("class") == "BTCheck_ON") {
        getSpecSecret = true;
    }

    var param = { 'userName': name, 'password': pwd, 'get_spec_secret': getSpecSecret, 'get_service_ticket': getServiceTicket };

    BingoTouch.SSO.Login('PASSWORD', param, function (ret) {
        //自动登录
        if ($("#cbAuto").attr("class") == "BTCheck_ON") {
            BingoTouch.Local.saveHashmap("loginHashMap", "isRemember", "true");
            BingoTouch.Local.saveHashmap("loginHashMap", "username", $("#userName").val());
            BingoTouch.Local.saveHashmap("loginHashMap", "token", ret.token.id);
            BingoTouch.Local.saveHashmap("loginHashMap", "spec_secret", ret.appSpecifiedSecret.id);
            BingoTouch.Local.saveHashmap("loginHashMap", "spec_secret_expires", ret.appSpecifiedSecret.expires);
            BingoTouch.Local.saveHashmap("loginHashMap", "loginId", ret.principal.id);
            BingoTouch.Local.saveHashmap("loginHashMap", "isAutoLogin", "true");
        }
        BingoTouch.Local.saveHashmap("loginHashMap", "obj", BingoTouch.Common.json2string(ret));

        AfterSSOLogin();

    }, function (code, desc) {
        BingoTouch.Common.alert('sso:' + code + ":" + desc);
    });
}

function AutoLogin() {
    var strLoginObj = BingoTouch.Local.readHashmap("loginHashMap", "obj");
    var authentication = BingoTouch.Common.string2json(strLoginObj);
    BingoTouch.Common.WebRequest(CheckLocalUser + authentication.principal.id, "GET", "", "", false,
        function (response) {
            BingoTouch.WebView.wait(false);

            if (!!!BingoTouch.Common.string2json(response).returnValue) {
                BingoTouch.Common.alert('对不起，您的信息未同步，请与许鹏联系。');
                return;
            } else {
                //登陆成功，缓存当前用户信息，然后进入首页
                var url = GetUserByLoginId + authentication.principal.id
                ReqGet(url, true, function (userInfo) {
                    BingoTouch.Local.saveHashmap("loginHashMap", "currentUser", BingoTouch.Common.json2string(userInfo));
                    BingoTouch.WebView.load("home.html");
                });
            }
        }, function (msg) {
            BingoTouch.Common.alert('CheckLocalUser:' + authentication.principal.id + msg);
            BingoTouch.WebView.wait(false);
    });

}

function AfterSSOLogin() {
    ////login to my App Server
    LoginToAppServer(context_path, "home.html", null);
}

function LoginToAppServer(serverPath, redictUrl, data) {
    /*获取登录后的回调对象*/
    var loginObj = BingoTouch.Local.readHashmap("loginHashMap", "obj");

    _path = serverPath;
    _data= data;
    _redictUrl = redictUrl;
    var obj = {
        _path: serverPath,
        _data: data,
        _redictUrl: redictUrl,
        success: function (ret) {
            //BingoTouch.Common.WebRequest(this._path + "ssoclient/login/serviceticket?openid.ex.service_ticket=" + ret, "POST", "", "", false,
            //function (response) {
                if (this._redictUrl != "") {
                    var strLoginObj = BingoTouch.Local.readHashmap("loginHashMap", "obj");
                    var authentication = BingoTouch.Common.string2json(strLoginObj);
                    BingoTouch.Common.WebRequest(CheckLocalUser + authentication.principal.id, "GET", "", "", false,
                    function (response) {
                        BingoTouch.WebView.wait(false);

                        if (!!!BingoTouch.Common.string2json(response).returnValue) {
                            BingoTouch.Common.alert('对不起，您的信息未同步，请与许鹏联系。');
                            return;
                        } else {
                            //登陆成功，缓存当前用户信息，然后进入首页
                            var url = GetUserByLoginId + authentication.principal.id
                            ReqGet(url, true, function (userInfo) {
                                BingoTouch.Local.saveHashmap("loginHashMap", "currentUser", BingoTouch.Common.json2string(userInfo));
                                BingoTouch.WebView.load(this._redictUrl);
                            });
                        }
                    }, function (msg) {
                        BingoTouch.Common.alert('CheckLocalUser:' + authentication.principal.id + msg);
                        BingoTouch.WebView.wait(false);
                    });
                }
            //},
            //function (code, desc) {
            //    BingoTouch.Common.alert("请求ServiceTicket失败!" + desc);
            //});
        },
        error: function (code, desc) {
            BingoTouch.Common.alert("请求ServiceTicket失败!" + desc);
        }
    };
    BingoTouch.SSO.ServiceTicket(BingoTouch.Common.string2json(loginObj), obj.success,obj.error);
}